﻿using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace LogHelper
{
    /// <summary>
    /// 日志操作类
    /// </summary>
    public class Log
    {
        /// <summary>
        /// 日志配置文件路径
        /// </summary>
        public static string LogConfigPath = AppDomain.CurrentDomain.BaseDirectory + @"Config\log4net.config";

        /// <summary>
        /// 初始化log4net
        /// </summary>
        public static void Init()
        {
            //初始化log4net
            XmlConfigurator.ConfigureAndWatch(new FileInfo(LogConfigPath));
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="level">日志级别</param>
        /// <param name="logcontent">日志内容</param>
        private static void Save(string level, object content)
        {
            //获取调用写日志方法的类名,release模式下inline方法会丢失堆栈跟踪，取消
            //System.Diagnostics.StackTrace trace = new StackTrace();
            //Type type = trace.GetFrame(2).GetMethod().DeclaringType;
            //ILog log = LogManager.GetLogger(type);
            ILog log = LogManager.GetLogger(level);
            //增加自定义信息写入到输出的日志对象属性，通过%property{属性名}获取
            PropertyInfo[] props = content.GetType().GetProperties();
            foreach (PropertyInfo prop in props)
            {
                object value = prop != null ? prop.GetValue(content, null) : null;
                LogicalThreadContext.Properties[prop.Name] = value;
            }
            switch (level.ToLower())
            {
                case "info": log.Info(content); break;
                case "warn": log.Warn(content); break;
                case "error": log.Error(content); break;
                case "fatal": log.Fatal(content); break;
                default: log.Debug(content); break;
            }

        }

        /// <summary>
        /// 调试日志
        /// </summary>
        /// <param name="logcontent">日志内容</param>
        public static void Debug(object logcontent)
        {
            Save("debug", logcontent);
        }

        /// <summary>
        /// 运行时日志
        /// </summary>
        /// <param name="logcontent">日志内容</param>
        public static void Info(object logcontent)
        {
            Save("info", logcontent);
        }

        /// <summary>
        /// 警告日志
        /// </summary>
        /// <param name="logcontent">日志内容</param>
        public static void Warn(object logcontent)
        {
            Save("warn", logcontent);
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="logcontent">日志内容</param>
        public static void Error(object logcontent)
        {
            Save("error", logcontent);
        }

        /// <summary>
        /// 严重错误日志
        /// </summary>
        /// <param name="logcontent">日志内容</param>
        public static void Fatal(object logcontent)
        {
            Save("fatal", logcontent);
        }

    }
}
